package com.mego.weblink.activitys;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.alibaba.fastjson.JSONObject;
import com.mego.weblink.BuildConfig;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.model.Deviceurl;
import com.mego.weblink.utils.HttpRequest;
import com.mego.weblink.version.UpdateManager;

import java.io.File;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.SystemBarTintManager;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.ItemDialog;
import zuo.biao.library.ui.WebViewActivity;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.MD5Util;
import zuo.biao.library.util.StringUtil;

public class MainActivity extends BaseActivity implements View.OnClickListener, ItemDialog.OnDialogItemClickListener, AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener, UpdateManager.InstallCallBack {


    private final String TAG = "MainActivity";
    public static final String INTENT_RANGE = "INTENT_RANGE";
    public static final String RESULT_CLICKED_ITEM = "RESULT_CLICKED_ITEM";

    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main_activity);

        //apk版本升级
//        UpdateManager.getUpdateManager().checkAppUpdate(this, this, false);
//        GPSProvider.getInstance().initGPSProvider(this);

        tintManager.setStatusBarTintEnabled(false);

        initView();
        initData();
        initEvent();


    }

    public static final String MEGO_TP = "http://eggi.megowx.com/";
    private ProgressBar pbWebView;
    private WebView wvWebView;

    @Override
    public void initView() {
        pbWebView = findView(R.id.pbWebView);
        wvWebView = findView(R.id.wvWebView);
    }

    @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
    @Override
    public void initData() {

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                pbWebView.setProgress(newProgress);
            }
        });

        wvWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pbWebView.setVisibility(View.GONE);
            }
        });

        HttpRequest.getweblink(getDeviceId(), 0, new OnHttpResponseListener() {

            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                try {//如果服务器返回的json一定在最外层有个data，可以用OnHttpResponseListenerImpl解析
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                    Deviceurl user = JSON.parseObject(data, Deviceurl.class);
                    wvWebView.loadUrl(user.getUrl());
                } catch (Exception e1) {
                    Log.e(TAG, "onHttpResponse  try { user = Json.parseObject(... >>" +
                            " } catch (JSONException e1) {\n" + e1.getMessage());
                }

            }
        });
    }


    @Override
    public void onBackPressed() {
        if (wvWebView.canGoBack()) {
            wvWebView.goBack();
            return;
        }

        super.onBackPressed();
    }


    @Override
    public void initEvent() {
        findViewById(R.id.tv_exit).setOnClickListener(this);
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    public void onForwardClick(View v) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_exit:
                moveTaskToBack(true); //Activity不销毁，直接进入后台
                break;

        }
    }

    private long firstTime = 0;//第一次返回按钮计时

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
            case KeyEvent.KEYCODE_BACK:
//                onExit();
//                return true;
                break;
        }

        return super.onKeyUp(keyCode, event);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
            System.exit(0);
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }
        if (requestCode == 100) {

        }
    }

    @Override
    public void onDialogItemClick(int requestCode, int position, String item) {

    }

    ProgressDialog mPB;
    public static final int INITFINISH = 1101;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == INITFINISH) {
                if (mPB != null) {
                    mPB.dismiss();
                    mPB = null;
                }
            }
        }
    };

    private final int REQUEST_TO_DOPAY = 25;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
        }
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {

    }

    @Override
    public void onTimerStop() {

    }

    @Override
    protected void onResume() {
        wvWebView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        wvWebView.onPause();
    }

    @Override
    protected void onDestroy() {
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }
        super.onDestroy();
    }

    private String getDeviceId() {

        SystemAllInfo info = SystemCenter.getInstance().getSysInfo("SERIAL");
        if (info == null) {
            //自动生成IMEI
            String code = Build.SERIAL;
            if (code.isEmpty() || code.compareToIgnoreCase("unknown") == 0) {
                code = MD5Util.MD5(System.currentTimeMillis() + Build.PRODUCT);
            }
            int max = 15;
            int size = code.length();
            if (size < max) {
                for (int i = size; i < max; i++) {
                    code += "0";
                }
            } else if (size > max) {
                code = code.substring(size - max);
            }
            info = new SystemAllInfo(null, "SERIAL", code.toLowerCase());
            SystemCenter.getInstance().saveSysInfo(info);
        }

        return info.getContent();
    }

    //<--- 安装apk---
    String apkpath = "";

    void installAPK(String filePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            /* Android N 写法*/
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", new File(apkpath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            /* Android N之前的老版本写法*/
            intent.setDataAndType(Uri.fromFile(new File(apkpath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            installAPK(apkpath);
        }
    }

    @Override
    public void doInstall(String filePath) {

        apkpath = filePath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                installAPK(apkpath);
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }
    //---安装apk--->

}

